/**统一登录js文件**/
import $ajax from '../../api/config'
var bIE9=false;

var http = 'http://192.168.100.146:8011'

if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/[6789]./i)) { 
	bIE9=true
}
var wsUrl = "ws"+(!bIE9&&"https:"==document.location.protocol?"s":"")+"://"+http+"/jyop/ws";
var ws = "";
var qrCodeTime = 0;
var isLogin = false;//登录状态
var qrCodeKey = "";

//心跳检测
var WebSocketHeartCheck = function(scoketType){
	this.lockReconnect = false;//避免重复连接
    this.timeout = 5000;//60秒
    this.timeoutObj = null;
    this.serverTimeoutObj = null;
    this.reset = function(){
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    }
    this.start = function(w,f){
		if(f){
			return;
		}
        var self = this;
        this.timeoutObj = setTimeout(function(){
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
			if(w.readyState==1){
            	w.send("HeartBeat");
			}
            self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
				//用自己的超时，如果用w.colse()执行之后，大概要一分钟才会执行webscoket自己的close方法，时间太长
				//进行ajax轮询
				if(scoketType=="login"){
					LoginPolling.isPostLoginPolling = true;
				}
                w.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout);
        }, this.timeout);
    }
}
//轮询查询
var LoginPolling = {
	isPostLoginPolling: false,//是否发起轮询请求
	loginPollingInterval: null,
	initInterval: null,
	init: function(){
		//防止重复调用
		if(this.initInterval != null){
			return;
		}
		//先发一个消息，保存session
		this.postId();
		this.initInterval = setInterval(this.postId,3000);
	},
	postId: function(){
		$ajax.post('/jyop/wxLoginPolling',{
			reqType: 1,
			id: qrCodeKey			
		}).then(function(){
			clearInterval(LoginPolling.initInterval);
			LoginPolling.initInterval = null;
		});
	},
	start: function(){
		//防止重复调用
		if(this.loginPollingInterval != null){
			return;
		}
		//定时器，定时请求看是否扫码登录，返回用户信息，登录
		this.loginPollingInterval = setInterval(function(){
			//如果浏览器不支持webscoket，走ajax轮询方式
			if(window.WebSocket == undefined) {
				LoginPolling.isPostLoginPolling = true;
			}
			if(!LoginPolling.isPostLoginPolling){
				return;
			}
			$ajax.post("/jyop/wxLoginPolling",{
				reqType:2
			}).then(function(data){
				loginCallBack(r);
			});
		},5000);
	},
	stop: function(){
		clearInterval(this.loginPollingInterval);
		this.loginPollingInterval = null;
		this.isPostLoginPolling = false;
	}
}
var webSocketHeartCheck = new WebSocketHeartCheck("login");
//创建websocket连接
var createWebSocket = function(flag){
	try{
		ws = new WebSocket(wsUrl);//实例化websocket对象
		initEventHandle(flag);
	}catch(e){
		reconnect();
		//console.log(e)
	}
}
//
var initEventHandle = function(flag){
	ws.onmessage = function(e){
		//接收消息正常，就不再发ajax轮询
		LoginPolling.isPostLoginPolling = false;
		if(e.data==""){
			return
		}else if(e.data=="HeartBeat"){//心跳检测
			//如果获取到消息，心跳检测重置
	        //拿到任何消息都说明当前连接是正常的
	        webSocketHeartCheck.reset().start(ws,isLogin);
			return;
		}
		//用户登录
		loginCallBack($.parseJSON(e.data));
	}
	ws.onerror = function(e){
		//console.info("onerror");
		reconnect();
	}
	ws.onclose = function(e) {
		//console.info("onclose");
        reconnect();
    }
	ws.onopen = function(e) {
		if(flag){//重连之后发送shareid
			SendMsg();
		}
		//心跳检测重置
        webSocketHeartCheck.reset().start(ws,isLogin);
	}
}
//
function reconnect() {
	if(webSocketHeartCheck.lockReconnect || isLogin){
		return;
	}
	LoginPolling.isPostLoginPolling = true;
    webSocketHeartCheck.lockReconnect = true;
	LoginPolling.init();
    //没连接上会一直重连，设置延迟避免请求过多
    setTimeout(function () {
        createWebSocket(true);
		webSocketHeartCheck.lockReconnect = false;
    }, 2000);
}
//超时重新加载二维码 
var qrCodeTimeout = function(){
	setInterval(function(){
		qrCodeTime++;
		if(qrCodeTime>30*60){
			loadQrCode();
			qrCodeTime = 0;
		}
	},1000);
	LoginPolling.init();
	SendMsg();
}
var SendMsg = function(){
	//向后台发送websocket数据
	if (window["WebSocket"]){
		if(ws.readyState==1){
			console.log("发送："+qrCodeKey)
			ws.send(qrCodeKey);
		}else{
			LoginPolling.isPostLoginPolling = true;
		}
	}else{
		LoginPolling.isPostLoginPolling = true;
	}
}
//生成页面二维码，不同页面处理逻辑
function loadQrCode(){
	if(isLogin){
		return;
	}
	var oldQrCodeKey = "";
	if(localStorage && typeof(localStorage.qrCodeKey) != "undefined"){
		oldQrCodeKey = localStorage.qrCodeKey;
	}
	if(oldQrCodeKey != ""){
		qrCodeKey = oldQrCodeKey;
		// qr/key
	}else{
		$ajax.post("/jyop/getQrCode",{qrCodeKey:oldQrCodeKey},function(key){
			console.info(key)
			qrCodeKey = key;
			localStorage.setItem("qrCodeKey",qrCodeKey);
			// qr/key
		});
	}
	setTimeout(function(){
		qrCodeTimeout();
	},500);
}

//查询用户信息，响应页面登录信息
function loginCallBack(data){
	console.info(data)
	if(data.status == 1){
		isLogin = true;
		//登录成功，停止轮询
		LoginPolling.stop();
		//登录成功，停止心跳监测
		webSocketHeartCheck.reset();
		if(ws.readyState==1){
			ws.send("close");
			ws.close();
		}
	}
}

//退出登录
function signout(){
	LoginPolling.start();
	createWebSocket(false);
	loadQrCode();
	isLogin = false;
	$ajax.post("/jyop/signOut",function(data){
		if(data=="ok"){
			try{
				$.cookie("userid_secure","",{expires:-1,path:"/"});
			}catch(e){
				document.cookie = "userid_secure=;expires=-1;path=/";
			}
		}
	})
}
haslogin();
//查看用户是否已经登录
function haslogin(){
	$ajax.post("/jyop/hasLogin",function(data){
		console.log(data)
		if(data.status == 1){
			isLogin = true;
			return true;
		}else{
			isLogin = false;
			loadQrCode();
			LoginPolling.start();
			createWebSocket(false);
			return false;
		}
	});
	
}